console.log("content::run in page");

document.addEventListener('DOMContentLoaded', function ()
{

    var installNode = document.createElement('div');
    installNode.id = '--webkit-call-bridge';
    installNode.style.display = 'none';
    installNode.innerText = "this a bridge tag";

    document.body.appendChild(installNode);

    console.log("content::install a js bridge");

    let port = chrome.runtime.connect();

    port?.onMessage.addListener((backjson, port) =>
    {
        //from background
        // console.log("content::from background:" + backjson);

        //sent to page
        var sendE: CustomEvent = document.createEvent("CustomEvent");
        sendE.initCustomEvent("--content2user", true, true, backjson);
        installNode.dispatchEvent(sendE);
    });

    //传声筒，直接作为和Background通讯的传声筒
    installNode.addEventListener("--user2content", (ev: Event) =>
    {
        //from page
        var event = ev as CustomEvent;
        var json = event.detail;
        if (json["cmd"] == "access.request" && json["path"] != undefined)
        {
            if (!confirm("你的页面正试图通过插件直接访问本地硬盘位置" + json["path"] + "，是否同意"))
            {
                return;
            }
        }
        //send to background
        port.postMessage(json);

    });
}
);
